﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using MyDMS.DAL;
using System.Linq;

/// <summary>
/// Summary description for PageBaseClass
/// </summary>
public class PageBaseClass : Page
{
    private const string RootPath = "/MyDMS";
    public static Author Author;
    private static readonly MyDMSEntity MyDmsEntity=new MyDMSEntity();

    public PageBaseClass()
    {
        this.Load += new EventHandler(PageBase_Load);
    }

    void PageBase_Load(object sender, EventArgs e)
    {
        if (Session["Author"] != null)
            Author = (Author)Session["Author"];
        else
        {
            string redirectUrl = Request.Url.AbsolutePath.Remove(Request.Url.AbsolutePath.LastIndexOf('/'))+ "/Login.aspx";
            Response.Redirect(redirectUrl);
        }
    }

    public static bool AuthenticateAdmin(string userName, string password)
    {
        List<Office> ofc = MyDmsEntity.Office.Where(r => r.Account_Email == userName).ToList();
        if (ofc.Count > 0)
        {
            if (ofc[0].Account_Password == password)
            {
                Author = new Author(ofc[0].Office_Code, ofc[0].Account_Email, ofc[0].Office_Code, true,0,0);
                return true;
            }
        }
        return false;
    }

    public static  bool AuthenticateUser(string userName, string password)
    {
        User user =
            MyDmsEntity.User.FirstOrDefault(r => (r.User_Name == userName) && (r.User_Password == password));
        if (user!=null)
        {
            int dept_code = user.Department_Code;
            int userOfc_Code = MyDmsEntity.Department.FirstOrDefault(r => r.Department_Code ==dept_code).Office_Code;
            int role_code = MyDmsEntity.UserInRole.FirstOrDefault(r => r.User_Code == user.User_Code).Role_Code;
            Author = new Author(user.User_Code, user.User_Name, userOfc_Code, false, dept_code, role_code);
            return true;
        }
        return false;
    }

}
